﻿using Entity;
using Entity.Dto;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;

namespace Application
{
    public class UserIdentyService
    {
        readonly DataContext dbContext;
        public UserIdentyService(DataContext dbContext)
        {
            this.dbContext = dbContext;
        }
        public ApiResult DapperList()
        {
            using (var connect = DbComponent.Connection)
            {
                var users= connect.Query<User>("SELECT * FROM Users").ToList();
                return ApiResult.Success(users);
            }
        }
        public ApiResult List()
        {
            return ApiResult.Success(dbContext.Users.Include(p=>p.Roles).ToList());
        }

        public ApiResult Login(LogInRequest request)
        {
            var response = new ApiResult();

            var user = dbContext.Users.FirstOrDefault(p => p.Account == request.Account);

            if (user == null)
            {
                return ApiResult.Fail("账户不存在");
            }


            return response;
        }

        public ApiResult Regist(User request)
        {
            var result = new ApiResult();
            result = VerifyInput(request);

            if (!result.IsSuccess) return result;
            var role = dbContext.Roles.FirstOrDefault(p => p.Id == 1);
            request.Roles.Add(role);
            var user = dbContext.Users.Add(request);
            dbContext.SaveChanges();
            return result;
        }

        private ApiResult VerifyInput(User request)
        {
            var apiResult = new ApiResult();
            if (request == null) return ApiResult.Fail("注册信息不能为空");
            var user = dbContext.Users.FirstOrDefault(u => u.Account == request.Account);
            if (user != null) return ApiResult.Fail("账户注册信息已存在");
            
            return ApiResult.Success();
        }
    }
}
